﻿using Microsoft.Extensions.Options;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Guids;
using Volo.Abp.Localization;

namespace Volo.Abp.LanguageManagement.Data
{
    public class LanguageManagementDataSeedContributor : ITransientDependency, IDataSeedContributor
	{
		protected ILanguageRepository LanguageRepository { get; }

		protected IGuidGenerator GuidGenerator { get; }

		protected AbpLocalizationOptions Options { get; }

		protected IDataFilter<ISoftDelete> SoftDeleteFilter { get; }

		public LanguageManagementDataSeedContributor(ILanguageRepository languageRepository, IOptions<AbpLocalizationOptions> options, IGuidGenerator guidGenerator, IDataFilter<ISoftDelete> softDeleteFilter)
		{
			this.LanguageRepository = languageRepository;
			this.GuidGenerator = guidGenerator;
			this.SoftDeleteFilter = softDeleteFilter;
			this.Options = options.Value;
		}

		public virtual async Task SeedAsync(DataSeedContext context)
		{
			using (this.SoftDeleteFilter.Disable())
			{
				var existingLanguages = await this.LanguageRepository.GetListAsync();
				foreach (var language in this.Options.Languages)
				{
					var check = new CultureCheck();
					check.language = language;
					if (!existingLanguages.Any(x => x.Equals(check.language)))
					{
						await this.LanguageRepository.InsertAsync(new Language(this.GuidGenerator.Create(), check.language.CultureName, check.language.UiCultureName, check.language.DisplayName, check.language.FlagIcon, true));
					}
				}
			}
		}

		private sealed class CultureCheck
		{

			internal bool IsCulture(Language l)
			{
				return l.CultureName == this.language.CultureName && l.UiCultureName == this.language.UiCultureName;
			}

			public LanguageInfo language;
		}
	}
}
